# -*- coding: utf-8 -*-
import hashlib
import logging
import requests

from common.bankcard.model import *

from common.bankcard import db as bankcard_db
from common.third.tonglue_balance import tonglue_get_balance

from common.utils import exceptions as err
from common.utils.telegram import send_text_msg_tele

_LOGGER = logging.getLogger('worker')


def fetch_all_card_balance():
    # 最多获取前1000张卡的余额
    bankcards, total_count = bankcard_db.list_bankcard({'$size':'-1'})
    for bankcard in bankcards:
        balance = tonglue_get_balance(bankcard.account_number, BANK_DCT[bankcard.bank])
        _LOGGER.info('%s with tonglue balance %s' % (bankcard.account_number, balance))
        bankcard.real_balance = balance
        bankcard.save()
    return True


def _get_all_bankcard_peroid():
    bankcard_period_data = {}
    bankcard_peroids = bankcard_db.get_all_bankcard_peroid()
    for peroid in bankcard_peroids:
        if peroid.bank not in bankcard_period_data:
            bankcard_period_data[peroid.bank] = {
                BANK_CARD_TYPE.TEST: {},
                BANK_CARD_TYPE.RECHARGE: {},
                BANK_CARD_TYPE.WITHDRAW: {}
            }
        bankcard_period_data[peroid.bank][peroid.card_type] = peroid.as_dict()
    return bankcard_period_data


def _card_reached_limit(bankcard_data, peroid, bankcard):
    reached_daily_limit, reached_limit = 0, 0
    if peroid and bankcard_data:
        if bankcard.card_type == BANK_CARD_TYPE.RECHARGE:
            if bankcard_data['daily_recharge_count'] >= peroid['daily_max_recharge_count']:
                reached_daily_limit = 1
            if bankcard_data['daily_recharge_total'] >= peroid['daily_max_recharge']:
                reached_daily_limit = 1
            if bankcard_data['recharge_total'] >= peroid['max_recharge']:
                reached_limit = 1
        elif bankcard.card_type == BANK_CARD_TYPE.WITHDRAW:
            if bankcard_data['daily_withdraw_count'] >= peroid['daily_max_withdraw_count']:
                reached_daily_limit = 1
            if bankcard_data['daily_withdraw_total'] >= peroid['daily_max_withdraw']:
                reached_daily_limit = 1
            if bankcard_data['withdraw_total'] >= peroid['max_withdraw']:
                reached_limit = 1
    return reached_daily_limit, reached_limit


def check_bankcard_limit():
    bankcard_period_data = _get_all_bankcard_peroid()
    bankcard_stat_data = bankcard_db.get_all_bankcard_data()
    bankcards = bankcard_db.get_all_bankcards()
    for bankcard in bankcards:
        peroid = bankcard_period_data.get(bankcard.bank, {}).get(bankcard.card_type)
        bankcard_data = bankcard_stat_data.get(bankcard.id)
        reached_daily_limit, reached_limit = _card_reached_limit(bankcard_data, peroid, bankcard)
        _LOGGER.info('check bankcard %s limit status: daily %s, total %s' % (bankcard.name,           reached_daily_limit, reached_limit))
        if bankcard.reached_limit != reached_limit \
            or bankcard.reached_daily_limit != reached_daily_limit:
            _LOGGER.info('update bankcard %s limit status: daily %s, total %s' % (bankcard.name, reached_daily_limit, reached_limit))
            bankcard.reached_daily_limit = reached_daily_limit
            bankcard.reached_limit = reached_limit
            bankcard.save()
            if reached_limit:
                send_text_msg_tele(u'卡号%s达到总限额' % bankcard.name)
            if reached_daily_limit:
                send_text_msg_tele(u'卡号%s达到单日限额' % bankcard.name)
    return True

